package com.cynteka.cyfoman.core;

import com.cynteka.cyfoman.core.IPropertyResolver;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * User: Sergey
 * Date: 01.08.11
 * Time: 19:52
 */
public class ComplexPropertyResolver implements IPropertyResolver {

    private Map<String, Object> nameLookup;

    private static final IPropertyResolver[] DEFAULT_RESOLVERS = new IPropertyResolver[]{
            new XMLPropertyResolver(),
            new ValueObjectPropertyResolver(),
            new FilePropertyResolver(),
            new MessagePropertyResolver(),
    };

    private List<IPropertyResolver> resolvers = Arrays.asList(DEFAULT_RESOLVERS);

    public List<IPropertyResolver> getResolvers() {
        return resolvers;
    }

    public void setResolvers(List<IPropertyResolver> resolvers) {
        this.resolvers = resolvers;
    }

    public Map<String, Object> getNameLookup() {
        return nameLookup;
    }

    public void setNameLookup(Map<String, Object> nameLookup) {
        this.nameLookup = nameLookup;
    }

    @Override
    public Object getProperty(Object object, String propertyName) {
        Object prop = lookupPropertyName(propertyName);

        Object res = null;
        if (prop instanceof List) {
            List lst = (List) prop;
            for (Object o : lst) {
                res = getProperty(object, String.valueOf(o));
                if (res != null)
                    break;
            }
        } else {
            for (IPropertyResolver resolver : resolvers) {
                res = resolver.getProperty(object, String.valueOf(prop));
                if (res != null)
                    break;
            }
        }
        return res;
    }

    protected Object lookupPropertyName(String name) {
        Object res = nameLookup == null ? null : nameLookup.get(name);
        if (res == null)
            res = name;
        return res;
    }
}
